<script>
	import licensePlateContent from './licensePlateContent.vue'
	import {
		createOrder,
		getWeighingRecord,
		orderPay,
		amend_config,
		getPoundBillDetail,
		lastPayedOrder
	} from '../../common/api.config.js'

	var Interval = null
	export default {
		components: {
			licensePlateContent
		},
		data() {
			return {
				remarkShow: false,
				queryFrom: {
					car_plate: '',
					goods_name: '',
					goods_exporter: '',
					goods_importer: '',
					print_type: '2',
					device_id: '',
					remark: '',
					weight: 0,
					weighing_type: 1,
					order_type: 1,
					complement_order_pid: ''
				},
				pay_id: '',
				ids: '',
				total_fee: '',
				payInfo: '',
				showComplete: false,
				fator: 0,
				payId: '',
				checkedIndex: 2
			}
		},
		onShow() {
			if (Interval || !uni.getStorageSync('token')) return
			console.log('onShow');
			if (this.ids) {
				Interval = setInterval(() => {
					this.getWeighing(this.ids)
				}, 1000)
			}
			if (this.payId) {
				this.checkPayStatus()
			}

		},
		onHide() {
			clearInterval(Interval)
			Interval = null
		},

		onUnload() {
			clearInterval(Interval)
			Interval = null
		},

		watch: {
			'queryFrom.car_plate': function(value) {
				console.log(value);
				this.get_amend_config(value)
			}
		},
		onLoad(e) {
			this.payId = ''
			let ids = ''
			console.log(e);
			if (uni.getStorageSync('device_id')) {
				ids = uni.getStorageSync('device_id')
				this.queryFrom.device_id = ids
			}

			// if (e.scene) {
			// 	ids = decodeURIComponent(e.scene).split('=')[1]
			// 	uni.setStorageSync('device_id', ids)
			// }

			if (e.scene) {
				ids = e.scene
				uni.setStorageSync('device_id', ids)
				this.queryFrom.device_id = ids
			}

			if (!uni.getStorageSync('token')) {
				// uni.clearStorageSync()
				console.log('relauch login page...')
				uni.reLaunch({
					url: '/pages/login/login'
				})
				return
			}

			this.ids = ids
			// this.ids = '21'
			// this.queryFrom.device_id = '21'
			if (this.ids == '') {
				uni.showModal({
					title: '提示',
					content: '设备ID是空的，请重新扫码进入小程序',
					showCancel: false
				});
				return
			} else {
				this.getLastPayedOrder()
			}
			// else{
			// 	this.$refs.typePopup.open()
			// }

			Interval = setInterval(() => {
				this.getWeighing(this.ids)
			}, 1000)


			// if (!uni.getStorageSync('token')) {
			// 	uni.clearStorageSync()
			// 	uni.reLaunch({
			// 		url: '/pages/login/login?device_id=' + ids
			// 	})
			// }else{
			// 	if(uni.getStorageSync('device_id')){
			// 		this.ids = uni.getStorageSync('device_id')
			// 		Interval = setInterval(()=>{
			// 			this.getWeighing(this.ids)
			// 		},1000)
			// 		uni.removeStorageSync('device_id');
			// 	}else{
			// 		Interval = setInterval(()=>{
			// 			this.getWeighing(this.ids)
			// 		},1000)
			// 	}
			// }
		},
		methods: {
			async getLastPayedOrder() {
				const {
					data,
					code,
					msg
				} = await lastPayedOrder()
				if (code == 1) {
					this.queryFrom.car_plate = data.car_plate
					this.$refs.licensePlateContentRef.plateNo = data.car_plate
					this.queryFrom.goods_name = data.goods_name
					this.queryFrom.goods_exporter = data.goods_exporter
					this.queryFrom.goods_importer = data.goods_importer
					this.queryFrom.weighing_type = data.weighing_type
					this.queryFrom.print_type = data.print_type
					this.checkedIndex = data.print_type
				}
			},
			async checkPayStatus() {
				var that = this
				const {
					data,
					code,
					msg
				} = await getPoundBillDetail({
					id: this.payId,
				})
				this.payId = ''
				console.log(data);
				if (code == 1) {
					if (data.status_name == "待付款") {
						// uni.showToast({
						// 	title: '您取消了支付',
						// 	icon: 'none'
						// })
						this.$refs.popup.close()
					} else if (data.status_name == "支付成功") {
						that.$refs.popup.close()
						that.$refs.payPopup.open('center')
						that.showComplete = true

						// clearInterval(Interval)
						// Interval = null
						// Interval = setInterval(()=>{
						// 	that.getWeighing(that.ids)
						// },1000)
						setTimeout(() => {
							that.showComplete = false
						}, 30000)
					}
				} else {
					uni.showToast({
						title: msg,
						icon: 'error'
					})
				}
			},
			async get_amend_config(car_plate) {
				const {
					data,
					code,
					msg
				} = await amend_config({
					car_plate,
					device_id: this.queryFrom.device_id
				})
				console.log(data);
				if (code == 1) {
					this.fator = data == null ? 0 : data.fator
				} else {
					uni.showToast({
						title: msg,
						icon: 'error'
					})
				}
			},
			async getWeighing(device_id) {
				const {
					data,
					code,
					msg
				} = await getWeighingRecord({
					device_id
				})
				// console.log(data, code);
				if (code == 1) {
					this.queryFrom.weight = data.weight / 1000
					const forData = data.weight / 1000
				} else {
					uni.showToast({
						title: msg,
						icon: 'none',
						mask: true
					})
				}

			},
			hideWeightFn(num) {
				console.log(num);
				const newNum = num.toString()
				return new Array(newNum.length).join('*') + newNum.charAt(newNum.length - 1)
			},
			changeTypeIndex(index) {
				this.queryFrom.weighing_type = index
			},
			printTypeChange(e) {
				this.queryFrom.print_type = e.detail.value
				this.checkedIndex = e.detail.value
			},
			async submit() {
				uni.showLoading({
					title: '请稍等'
				})
				// this.$refs.popup.open('center')	
				if (!this.queryFrom.car_plate) {
					uni.showToast({
						title: '请填写车牌',
						icon: 'none'
					})
					return
				}
				if (!this.queryFrom.print_type) {
					uni.showToast({
						title: '请选择磅单打印',
						icon: 'none'
					})
					return
				}
				// clearInterval(Interval)
				// Interval = null
				let forms = JSON.parse(JSON.stringify(this.queryFrom))
				if (this.fator) {
					forms.weight = this.queryFrom.weight * 1000 * (this.fator * 0.01)
				} else {
					forms.weight = this.queryFrom.weight * 1000
				}
				const {
					data,
					code,
					msg
				} = await createOrder(forms)
				uni.hideLoading()
				if (code == 1) {
					this.payId = data.id
					this.total_fee = data.total_fee
					this.getOrderPay(data.order_sn)
				} else {
					uni.showToast({
						title: msg,
						icon: 'error'
					})
				}
			},
			async getOrderPay(order_sn) {
				// 无需付款
				if (this.total_fee == 0) {
					this.$refs.popup.open('center')
					return
				}

				const {
					data,
					code,
					msg
				} = await orderPay({
					order_sn,
					pay_channel: 'bolink'
				})
				if (code == 1) {
					this.payInfo = data
					this.$refs.popup.open('center')

				} else {
					uni.showToast({
						title: msg,
						icon: 'error'
					})
				}
			},
			onPay() {
				// 无需付款
				if (this.total_fee == 0) {
					uni.showLoading({
						title: '请求中'
					})
					let that = this
					setTimeout(function() {
						uni.hideLoading()
						that.$refs.popup.close()
						that.$refs.payPopup.open('center')
						that.showComplete = true
						that.payId = ''
						
						setTimeout(() => {
							that.showComplete = false
							// console.log('timeout 30s', that.showComplete)
						}, 30000)
					}, 1000)
					return
				}

				uni.showLoading({
					title: '请求中'
				})
				var that = this
				wx.navigateToMiniProgram({
					appId: 'wxbd08b4baa10fcc1d',
					path: 'pages/pay/pay',
					extraData: {
						"sign": this.payInfo.sign,
						"union_id": this.payInfo.union_id,
						"data": {
							"amount": this.payInfo.data.amount,
							"trade_no": this.payInfo.data.trade_no,
							"title": this.payInfo.data.title,
							"park_id": this.payInfo.data.park_id,
							"pay_type": this.payInfo.data.pay_type,
							"description": this.payInfo.data.description,
							"channel": this.payInfo.data.channel,
							"time_temp": this.payInfo.data.time_temp,
						}
					},
					envVersion: 'release', //要打开的小程序版本 - 正式版
					success(res) {
						// 打开成功
						// console.log('hide loading')
						uni.hideLoading()
					}
				})

				// uni.requestPayment({
				// 	provider: 'wxpay',
				// 	timeStamp: this.payInfo.timestamp,
				// 	nonceStr: this.payInfo.noncestr,
				// 	package: this.payInfo.package,
				// 	signType: 'RSA',
				// 	paySign: this.payInfo.sign,
				// 	success: function(res) {
				// 		uni.hideLoading()
				// 		if (res.errMsg == 'requestPayment:ok') {
				// 			that.$refs.popup.close()
				// 			that.$refs.payPopup.open('center')
				// 			that.showComplete = true

				// 			// clearInterval(Interval)
				// 			// Interval = null
				// 			// Interval = setInterval(()=>{
				// 			// 	that.getWeighing(that.ids)
				// 			// },1000)
				// 			setTimeout(() => {
				// 				that.showComplete = false
				// 			}, 30000)
				// 		}
				// 	},
				// 	fail: function(err) {
				// 		console.log(err);
				// 	}
				// });
			},
			setPlate(e) {
				this.queryFrom.car_plate = e
			},
			popupChange({
				show
			}) {
				if (!show) {
					if (this.ids) {
						Interval = setInterval(() => {
							this.getWeighing(this.ids)
						}, 1000)
					}
				}
			}
		}
	}
</script>

<template>
	<view>
		<view class="kgBox" v-if="fator">
			{{(showComplete ? (queryFrom.weight * (fator * 0.01)).toFixed(2) : hideWeightFn((queryFrom.weight * (fator * 0.01)).toFixed(2))) || '0'}}kg
		</view>
		<view class="kgBox" v-else>
			{{(showComplete ? (queryFrom.weight) : hideWeightFn(queryFrom.weight)) || '0'}}kg
		</view>

		<view class="contentBox">
			<view class="typeBox u-flex u-row-evenly">
				<view :class="queryFrom.weighing_type == 1 ? 'ac' : 'notac'" @click="changeTypeIndex(1)">一次过磅</view>
				<view :class="queryFrom.weighing_type  == 2 ? 'ac' : 'notac'" @click="changeTypeIndex(2)">两次过磅</view>
				<!-- <view :class="typeIndex  == 2 ? 'ac' : 'notac'" @click="changeTypeIndex(2)">多次过磅</view> -->
			</view>
			<view class="title">
				<span style="color: red;">*</span>
				车牌号码(必填)
			</view>
			<licensePlateContent ref="licensePlateContentRef" @setPlate="setPlate" />
			<view class="title">
				货物名称(选填)
			</view>
			<input v-model="queryFrom.goods_name" type="text" class="inputBox bb" placeholder="请输入过磅的货物名称"
				placeholder-style="font-size: 28rpx;">
			<view class="title">
				送货方（选填）
			</view>
			<input v-model="queryFrom.goods_exporter" type="text" class="inputBox bb" placeholder="请输入送货方名称"
				placeholder-style="font-size: 28rpx;">
			<view class="title">
				收货方（选填）
			</view>
			<input v-model="queryFrom.goods_importer" type="text" class="inputBox bb" placeholder="请输入收货方名称"
				placeholder-style="font-size: 28rpx;">
			<view class="title">
				<span style="color: red;">*</span>
				磅单打印
			</view>
			<view class="u-flex u-row-between" style="margin-top: 18rpx;">
				<view class="u-flex">
					<radio-group @change="printTypeChange" class="u-flex">
						<radio style="margin-left: 32rpx;" value="1" :checked="checkedIndex == 1" />
						<view>
							一联磅单
						</view>
						<radio style="margin-left: 70rpx;" value="2" :checked="checkedIndex == 2" />
						<view>
							二联磅单
						</view>
						<radio style="margin-left: 70rpx;" value="3" :checked="checkedIndex == 3" />
						<view>
							三联磅单
						</view>
					</radio-group>
				</view>
			</view>
			<view class="submitButton" @click="submit">提交过磅</view>
		</view>

		<!-- 		<uni-popup ref="typePopup" type="center">
			<view class="u-flex-col u-col-center" style="width: 700rpx;height: 90vh;background-color: #f1dc27;">
				<image src="../../static/dollar_outlined@2x.png" style="width: 200rpx;height: 200rpx;" class="icon"
					mode=""></image>
				<view style="font-size: 36rpx;margin-top: 108rpx">过磅总费用</view>
				<view style="color: rgba(0, 0, 0, 1);font-weight: 900;font-size: 96rpx;margin-top: 14rpx;">
					¥{{total_fee}}</view>
				<view class="payButton" @click="onPay">立即支付</view>
			</view>
		</uni-popup> -->

		<uni-popup ref="popup" type="center">
			<view class="popupBox u-flex-col u-col-center">
				<image src="../../static/dollar_outlined@2x.png" style="width: 200rpx;height: 200rpx;" class="icon"
					mode=""></image>
				<view style="font-size: 36rpx;margin-top: 108rpx">过磅总费用</view>
				<view style="color: rgba(0, 0, 0, 1);font-weight: 900;font-size: 96rpx;margin-top: 14rpx;">
					¥{{total_fee}}</view>
				<view class="payButton" @click="onPay">立即支付</view>
			</view>
		</uni-popup>


		<uni-popup ref="payPopup" type="center">
			<view class="popupBox u-flex-col u-col-center">
				<image src="../../static/pay.png" style="width: 200rpx;height: 200rpx;" class="icon" mode=""></image>
				<view style="font-size: 36rpx;margin-top: 108rpx">¥{{total_fee}}</view>
				<view style="color: rgba(0, 0, 0, 1);font-weight: 900;font-size: 96rpx;margin-top: 14rpx;">支付成功</view>
				<textarea class="textareaBox bb" value="已提交打印请留意票据出口"></textarea>
			</view>
		</uni-popup>

	</view>
</template>

<style lang="scss">
	view {
		color: rgba(56, 56, 56, 1);
	}

	.popupBox {
		width: 666rpx;
		height: 600rpx;
		border-radius: 32rpx;
		background: rgba(255, 255, 255, 1);

		.textareaBox {
			width: 526rpx;
			height: 130rpx;
			opacity: 1;
			border-radius: 20rpx;
			background: rgba(245, 245, 245, 1);
			padding: 16rpx;
			margin-top: 14rpx;
		}

		.icon {
			position: absolute;
			top: -100rpx;
			left: 234rpx;
		}

		.payButton {
			width: 526rpx;
			height: 84rpx;
			line-height: 84rpx;
			border-radius: 42rpx;
			background: rgba(254, 240, 7, 1);
			font-weight: 500;
			text-align: center;
			margin-top: 100rpx;
		}
	}

	.submitButton {
		width: 686rpx;
		height: 84rpx;
		line-height: 84rpx;
		text-align: center;
		border-radius: 42rpx;
		background: rgba(254, 240, 7, 1);
		font-size: 32rpx;
		font-weight: 700;
		color: rgba(51, 51, 51, 1);
		margin: 56rpx 0 0 38rpx;
	}

	.kgBox {
		width: 750rpx;
		height: 280rpx;
		background-color: #f1dc27;
		font-size: 120rpx;
		font-weight: 900;
		line-height: 220rpx;
		color: rgba(0, 0, 0, 1);
		text-align: center;
	}

	.contentBox {
		width: 750rpx;
		// height: 300rpx;
		background-color: #fff;
		position: relative;
		border-radius: 36rpx;
		top: -32rpx;
		overflow: hidden;

		.inputBox {
			width: 686rpx;
			height: 80rpx;
			line-height: 80rpx;
			border-radius: 8rpx;
			background: rgba(247, 247, 247, 1);
			margin: 16rpx 0 0 32rpx;
			padding-left: 20rpx;
		}

		.title {
			font-size: 32rpx;
			font-weight: 400;
			color: rgba(29, 33, 41, 1);
			margin-left: 32rpx;
			margin-top: 24rpx;
		}
	}

	.typeBox {
		margin-top: 28rpx;
		margin-bottom: 8rpx;

		.notac {
			width: 296rpx;
			height: 80rpx;
			line-height: 80rpx;
			text-align: center;
			border-radius: 200rpx;
			background: rgba(229, 229, 229, 1);
			font-size: 28rpx;
			font-weight: 400;
			color: rgba(166, 166, 166, 1);
		}

		.ac {
			@extend .notac;
			background: rgba(255, 235, 59, 1);
			color: rgba(29, 33, 41, 1);
		}
	}
</style>
